﻿using Contract.Domain;
using Contract.Infrastructure.Repository;
using Contract.Read_WebApi.Application.Commands;
using MediatR;
using Microsoft.AspNetCore.Routing;
using Newtonsoft.Json;
using PublicCommon;
using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace Contract.Read_WebApi.Application.CommandHandler
{
    public class GetCoordinatesCommandHandler : IRequestHandler<GetCoordinatesCommands, Domain.Contract>
    {
        private readonly IRepository<Domain.Contract> repository;
        private readonly Cross_services_Helper cross_services_helper;

        public GetCoordinatesCommandHandler(IRepository<Domain.Contract> repository, Cross_services_Helper cross_services_helper)
        {
            this.repository = repository;
            this.cross_services_helper = cross_services_helper;
        }

        public async Task<Domain.Contract> Handle(GetCoordinatesCommands request, CancellationToken cancellationToken)
        {
            var info = await repository.GetAsync(x => x.ContractNumber == request.Number);
            var res = await cross_services_helper.Get($"http://10.31.60.9:8000/LongLine/api/LineInfo/GetLineRoute");
            var lines = JsonConvert.DeserializeObject<List<LineDto>>(res);
            var line = lines.Where(x => x.Id == info.Route).FirstOrDefault();
            var infos = new Domain.Contract();
            infos.ContractId = info.ContractId;
            infos.ContractNumber = info.ContractNumber;
            infos.ContractTitle = info.ContractTitle;
            infos.ShipperEnterprise = info.ShipperEnterprise;
            infos.ShipperPrincipal = info.ShipperPrincipal;
            infos.Route = line.Id;
            infos.TonTransport = info.TonTransport;
            infos.Tonnage = info.Tonnage;
            infos.CharterAmount = info.CharterAmount;
            infos.SigningDate = info.SigningDate;
            infos.Responsible = info.Responsible;
            infos.CreateDate = info.CreateDate;
            infos.AuditState = info.AuditState;
            infos.Approver = info.Approver;
            infos.startLat = info.startLat;
            infos.endLat = info.endLat;
            infos.startLng = info.startLng;
            infos.endLng = info.endLng;
            return infos;
        }
    }
}
